<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/**
 * 检查前端是否有权限 访问该模块
 */
class CheckWechatAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        //判断前台接口权限
        $wechat_port_auth = config('other.wechat_port_auth');
        $flag = false;
        if (!empty($wechat_port_auth)) {
            //获取控制器名称
            $controller_name = strtolower(str_ireplace('Controller', '', class_basename(Route::current()->controller)));
            //获取路由名称
            $uri = Route::current()->uri;
            $uri = explode('/', $uri);
            $uri = !empty($uri[1]) ? strtolower($uri[1]) : null;

            //所有人都有的权限
            $allow_auth = [
                'jwt',
                'index', 
                'wechatauth',
                'service',
                'useraccess',
                'userprotocol',
                'libinfo',
                'userinfo',
                'scanqr',
                'useraddress',
                'system',
                'systeminfo',
                'feedback',
            ];
            if (in_array($controller_name, $allow_auth) || ($uri && in_array($uri, $allow_auth))) {
                $flag = true;
            } else {
                foreach ($wechat_port_auth as $key => $val) {
                    if (strtolower($val) == $controller_name || ($uri && strtolower($val) == $uri)) {
                        $flag = true;
                        break;
                    }
                }
            }
        } else {
            $flag = true;
        }
        if (!$flag) {
            return  response()->json(['code' => 207, 'msg' => '无权使用该模块']);
        }

        return $next($request);
    }
}
